<template>
  <section>
    <!--工具条 高级查询-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <el-input v-model="filters.name" placeholder="姓名"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="deptQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <el-table :data="department" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
              style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="部门名称" width="120" sortable>
      </el-table-column>
      <el-table-column prop="sn" label="部门编号" width="120" sortable>
      </el-table-column>
      <el-table-column prop="parent.name" label="上级部门" width="120" sortable>
      </el-table-column>
      <el-table-column prop="manager.username" label="部门领导" width="120" sortable>
      </el-table-column>
      <el-table-column prop="state" label="是否启用" width="100" sortable>
        <template scope="scope">
        <el-span size="small" style="color: forestgreen" v-if="scope.row.state==1" >启用</el-span>
        <el-span size="small" style="color: red" v-else-if="scope.row.state==0" >禁用</el-span>
        <el-span size="small" style="color: gray" v-else>未知</el-span>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="150">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条 批量操作-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination
          layout="prev, pager, next"
          @current-change="handleCurrentChange"
          :page-size="pageSize"
          :total="totals"
          style="float:right;">
      </el-pagination>
    </el-col>



    <!--新增或修改界面-->
    <el-dialog :title="title" :visible.sync="addFormVisible" :close-on-click-modal="false">
      <el-form :model="addForm" label-width="80px" :rules="addFormRules" ref="addForm">
        <el-form-item label="部门编号" prop="sn">
          <el-input v-model="addForm.sn" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="addForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="addForm.state">
            <el-radio class="radio" :label="1">启用</el-radio>
            <el-radio class="radio" :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="部门领导" prop="manager_id">
<!--          <el-input v-model="addForm.parent_id" auto-complete="off"></el-input>-->
          <el-select v-model="addForm.manager_id" placeholder="请选择" clearable>
            <el-option
                v-for="item in employees"
                :label="item.username"
                :value="item.id"
                       >
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="上级部门" prop="parent_id">
<!--          <el-input v-model="addForm.manager_id" auto-complete="off"></el-input>-->
          <el-cascader v-model="addForm.parent_id"
              :options="deptTree"
              :props="{
                checkStrictly: true ,
                label: 'name',
                value: 'id'
              }"
              clearable>
          </el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="addFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="addLoading">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>

export default {
  data() {
    return {
      deptTree: [],
      employees: [],
      title: '',
      filters: {
        name: ''
      },
      department: [],
      totals: 0,
      currentPage: 1,
      pageSize: 10,
      listLoading: false,
      sels: [],//列表选中列



      addFormVisible: false,//新增界面是否显示
      addLoading: false,
      addFormRules: {
        sn: [
          {required: true, message: '请输入部门编号', trigger: 'blur'}
        ],
        name: [
          {required: true, message: '请输入部门名称', trigger: 'blur'}
        ]
      },
      //新增界面数据
      addForm: {
        id: null,
        sn: '',
        name: '',
        state: 1,
        manager_id: null,
        parent_id: null
      }

    }
  },
  methods: {
    getEmployees(){
      this.$http.get("/employee").then(res=>{
        this.employees = res.data;
      })
    },
    getDeptTree(){
      this.$http.get("/department/deptTree").then(res=>{
        this.deptTree = res.data;
      }).catch(res => {

      })
    },
    deptQuery() {
      this.currentPage = 1;
      this.getDepartment();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getDepartment();
    },
    //获取用户列表
    getDepartment() {
      let para = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        keywords: this.filters.name
      };
      // 开启忙等模式
      this.listLoading = true;
      this.$http.post("/department", para).then(res => {
        // 关闭忙等模式
        this.listLoading = false;

        this.department = res.data.rows;
        this.totals = res.data.totals;
      }).catch(res => {
        this.$message.error("系统繁忙，请稍后重试")
      })
    },
    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;

        this.$http.delete("/department/" + row.id).then((res=>{
          this.listLoading = false;

          if (res.data.success){
            this.$message({
              message: '删除成功',
              type: 'success'
            });
          }else{
            this.$message({
              message: res.data.message,
              type: 'error'
            });
          }
          this.getDepartment();
        })).catch(res=>{
          this.$message({
            message: "系统繁忙，请稍后重试",
            type: 'error'
          });
        })

        /*removeUser(para).then((res) => {
          this.listLoading = false;
          //NProgress.done();
          this.$message({
            message: '删除成功',
            type: 'success'
          });
          this.getDepartment();
        });*/
      }).catch(() => {

      });
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      this.getEmployees()
      this.getDeptTree();
      this.title = '编辑'
      this.addFormVisible = true;
      this.addForm = Object.assign({}, row);
      console.log(row)
    },
    //显示新增界面
    handleAdd: function () {
      this.getEmployees()
      this.getDeptTree();
      this.title = '新增',
      this.addFormVisible = true;
      this.addForm = {
        sn: '',
        name: '',
        state: 1,
        manager_id: null,
        parent_id: null
      };
    },

    //新增或修改
    saveSubmit: function () {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.addLoading = true;
            //NProgress.start();
            let para = Object.assign({}, this.addForm);

            let arr = para.parent_id;
            if (arr.length == 0 && arr){
              para.parent_id = null;
            }
            if(arr.length > 0){
              para.parent_id = arr[arr.length-1]
            }


            this.$http.put("/department", para).then(res => {
              this.addLoading = false;

              if (res.data.success){
                this.$message({
                  message: '提交成功',
                  type: 'success'
                });
              }else{
                this.$message({
                  message: res.data.message,
                  type: 'error'
                });
              }
              this.addFormVisible = false;
              this.getDepartment();
            }).catch(res => {
              this.addFormVisible = false;
              this.$message({
                message: '系统繁忙，请稍后重试',
                type: 'error'
              });
            })
            /*addUser(para).then((res) => {
              this.addLoading = false;
              //NProgress.done();
              this.$message({
                message: '提交成功',
                type: 'success'
              });
              this.$refs['addForm'].resetFields();
              this.addFormVisible = false;
              this.getDepartment();
            });*/
          });
        }
      });
    },
    selsChange: function (sels) {
      this.sels = sels;
    },
    //批量删除
    batchRemove: function () {
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;

        this.$http.patch("/department",ids).then((res=>{
          this.listLoading = false;

          if (res.data.success) {
            this.$message({
              message: '删除成功',
              type: 'success'
            });
          }else {
            this.$message({
              message: res.data.message,
              type: 'error'
            });
          }
          this.getDepartment();
        })).catch((res) => {
          this.$message({
            message: '系统错误，请稍后重试',
            type: 'error'
          });
        })

        /*batchRemoveUser(para).then((res) => {
          this.listLoading = false;
          //NProgress.done();
          this.$message({
            message: '删除成功',
            type: 'success'
          });
          this.getDepartment();
        });*/
      }).catch(() => {

      });
    }
  },
  mounted() {
    this.getDepartment();
  }
}

</script>

<style scoped>

</style>